package com.authine.cloudpivot.ext.controller;

import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.WorkflowInstanceFacade;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizPropertyModel;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizSchemaModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.status.WorkflowInstanceStatus;
import com.authine.cloudpivot.engine.enums.type.BizPropertyType;
import com.authine.cloudpivot.ext.service.AttachmentService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author hxd
 * @Date 2021/11/17 11:13
 * @Description poc 测试
 **/
@RestController
@RequestMapping("/public/poctest")
@Slf4j
public class PocTestController extends BaseController {


    @GetMapping("getUsersByRoleId")
    public ResponseResult getUsersByRoleId (@RequestParam String roleId){
        List<UserModel> list = Collections.emptyList();
        try {
            list = getOrganizationFacade().getUsersByRoleId(roleId);
        } catch (Exception e) {
            log.error("获取用户失败:{}",e);
            return getErrResponseResult(-1l,"系统异常");
        }

        return getOkResponseResult(list,"ok");
    }



    @GetMapping("getSiteId")
    public ResponseResult<String> getSiteId(){
        String id = UUID.randomUUID().toString().replaceAll("-","");
        return getOkResponseResult(id,"ok");
    }



    @GetMapping("getSSPApprovalInfo")
    public ResponseResult getSSPApprovalInfo(@RequestParam String bizId,@RequestParam String code){
        BizObjectFacade bizObjectFacade = getBizObjectFacade();

        Map<String, Object> rst = new HashMap<>();
        //默认ssp
        if (code == null) {
            code ="ssp";
        }

        // 判断ssp 是否已有ssp流程
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode(code);
        queryModel.setQueryCode(code);

        queryModel.setPageable(new PageableImpl(0,1));

        queryModel.setFilterExpr(Q.it("dzgz", FilterExpression.Op.Eq, bizId));

        queryModel.setOrderByFields(Collections.singletonList("createdTime"));

        queryModel.setOrderType(SortParameters.Order.DESC.ordinal());

        Page<BizObjectModel> page = bizObjectFacade.queryBizObjects(queryModel);

        if (page.getTotal()!=0){
            BizObjectModel bizObjectModel = page.getContent().get(0);
            String workflowInstanceId = bizObjectModel.getWorkflowInstanceId();

            if (workflowInstanceId!=null){
                WorkflowInstanceFacade instanceFacade = getWorkflowInstanceFacade();
                WorkflowInstanceModel workflowInstance = instanceFacade.getWorkflowInstance(workflowInstanceId);

                if (workflowInstance != null && workflowInstance.getState() != WorkflowInstanceStatus.CANCELED ) {
                    rst.put("instanceId",workflowInstanceId);
                    if( workflowInstance.getState() == WorkflowInstanceStatus.COMPLETED){
                        rst.put("state", true);
                    }
                }
            }
        }
        return getOkResponseResult(rst,"");
    }

    @Autowired
    AttachmentService attachmentService;

    @PostMapping("copy")
    public ResponseResult copy(@RequestBody Map<String,Object> map ){

        String code = (String) map.get("code");
        String id = (String) map.get("id");
        List<String> fileCodeList = (List<String>) map.get("fileCodeList");

        boolean b = getBizObjectFacade().existsBizObject(code, id);
        if (!b){
         return getErrResponseResult(-1L,"业务数据不存在");
        }

        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(code, id);
        //组合课程更新反馈数据
        BizSchemaModel bizSchemaModel = this.getAppManagementFacade().getBizSchemaBySchemaCode(code, true);

        //获取数据项code , 不是子表,已发布,不是默认字段
        List<String> fieldList = bizSchemaModel.getProperties().stream()
                .filter(prop -> !prop.getDefaultProperty() && prop.getPropertyType() != BizPropertyType.CHILD_TABLE && prop.getPublished())
                .map(BizPropertyModel::getCode).collect(Collectors.toList());

        //创建更新普通数据
        Map<String, Object> data = new HashMap<>();
        fieldList.forEach(f -> data.put(f, bizObject.get(f)));
        attachmentService.attachmentCopy(data, fileCodeList);

        BizObjectCreatedModel bizObjectCreatedModel = new BizObjectCreatedModel(code, data, false);

        String s = getBizObjectFacade().saveBizObject(getUserId(), bizObjectCreatedModel,false);

        return getOkResponseResult(s);


    }
}
